
import { View, Button } from '@tarojs/components';
import Taro, { useContext, useEffect, useState } from '@tarojs/taro';
import * as styles from './index.module.less';
import { toast } from "~/common/func.ts"
import { get, post } from '../request';
import { observer } from '@tarojs/mobx';
import mobxStore from "~/globalStore.ts"
interface PropsValue {
    name?: string | undefined,
    mobile?: string | undefined,
}

const Wechat = (props) => {
    const { user, changeUser } = useContext(mobxStore)
    // 授权
    const getUserInfo = async (event) => {
        const Info = event.target ? event.detail.userInfo : null;
        if (!Info) {
            toast.none('拒绝授权，将无法使用本小程序全部功能，请重新获取授权')
            return;
        }
        const res = await Taro.login();
        const { userInfo } = await Taro.getUserInfo();
        const params = {
            headimgurl: userInfo.avatarUrl,
            nickname: userInfo.nickName,
            code: res.code
        };
        const { data } = await get('wx/wx-token', params)
        Taro.setStorageSync('token', data);
        const val = await get('wx/info')
        changeUser({ ...val.data })
        toast.success("获取成功")
    }
    // 授权和获取手机号
    const getPhoneNumber = async (event) => {
        const userInfo = event.target ? event.detail.encryptedData : null;
        if (!userInfo) {
            toast.none('拒绝获取，将无法使用本小程序全部功能，请重新获取获取！')
            return;
        }
        const res = await Taro.login();
        const params = {
            encrypted: event.detail.encryptedData,
            code: res.code,
            iv: event.detail.iv
        };
        await get('wx/decodeUserInfo', params)
        const val = await get('wx/info')
        changeUser({ ...val.data })
        toast.success("获取成功")
    }
    return (
        <View style={{ width: "100%" }}>
            {
                !user.nickname && <Button className={styles.btn} open-type="getUserInfo" onGetUserInfo={(event) => getUserInfo(event)} type="default" hover-class="none">
                    {props.children}
                </Button>
            }
            {
                !user.mobile && <Button className={styles.btn} open-type="getPhoneNumber" onGetPhoneNumber={(event) => getPhoneNumber(event)} type="default" hover-class="none">
                    {props.children}
                </Button>
            }

        </View>
    )
}
export default observer(Wechat)